import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zhaoxiaowu_app/components/view.dart';
import 'package:zhaoxiaowu_app/global/global.dart';
import 'package:zhaoxiaowu_app/utils/event_bus.dart';
import 'package:zhaoxiaowu_app/utils/utils.dart';
import 'package:zhaoxiaowu_app/viewmodels/login_viewmodel.dart';

class LoginView extends StatefulWidget {
  @override
  _LoginViewState createState() => _LoginViewState();
}

class _LoginViewState extends State<LoginView> {
  TextEditingController _username = TextEditingController();
  TextEditingController _password = TextEditingController();
  GlobalKey _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();

    bus.on("fail", (arg) {
      if (arg["view"] == "login") {
        ToastUtils.showToast(arg["message"]);
      }
    });

    loadData();
  }

  @override
  void dispose() {
    _username.dispose();
    _password.dispose();
    super.dispose();
    bus.off("fail");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar("登录"),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Column(
            children: [
              _getTopImageWidget(),
              SizedBox(height: 16),
              Form(
                key: _formKey,
                child: Column(
                  children: [
                    _getUsernameWidget(),
                    _getPasswordWidget(),
                  ],
                ),
              ),
              SizedBox(height: 16),
              _getForgotPasswordWidget(),
              SizedBox(height: 16),
              _getLoginButtonWidget(),
              SizedBox(height: 8),
              _getRegisterButtonWidget(),
            ],
          ),
        ),
      ),
    );
  }

  void loadData() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    final token = sp.getString("token");
    if (token != null) {
      Global.shared().setHeaders(token);
      context.read<LoginViewModel>().tokenLogin(token);
    }
  }

  void _login() {
    if ((_formKey.currentState as FormState).validate()) {
      final viewModel = this.context.read<LoginViewModel>();
      viewModel.login(_username.text, _password.text);
    }
  }

  void _register() {
    dynamic params = Navigator.of(this.context).pushNamed("register");
    if (params != null) {
      _username = params["account"];
      _password = params["password"];
    }
  }

  Widget _getRegisterButtonWidget() {
    return Container(
      width: double.infinity,
      height: 30,
      child: ElevatedButton(
        child: Text("注 册"),
        onPressed: _register,
      ),
    );
  }

  Widget _getLoginButtonWidget() {
    return Container(
      width: double.infinity,
      child: ElevatedButton(
        child: Text("登 录"),
        onPressed: _login,
      ),
    );
  }

  Widget _getForgotPasswordWidget() {
    return GestureDetector(
      child: Container(
        width: double.infinity,
        child: Text(
          "忘记密码",
          style: TextStyle(color: Colors.blue),
          textAlign: TextAlign.right,
        ),
      ),
      onTap: () => print("忘记密码"),
    );
  }

  Widget _getPasswordWidget() {
    return TextFormField(
      controller: _password,
      decoration: InputDecoration(
        labelText: "密码",
        hintText: "请输入密码",
        icon: Icon(Icons.lock),
      ),
      textInputAction: TextInputAction.send,
      obscureText: true,
      // validator: (value) {
      //   return value!.trim().length > 0 ? null : "密码不能为空";
      // },
    );
  }

  Widget _getUsernameWidget() {
    return TextFormField(
      // autofocus: true,
      controller: _username,
      decoration: InputDecoration(
        labelText: "账号",
        hintText: "请输入账号",
        icon: Icon(Icons.person),
      ),
      textInputAction: TextInputAction.next,
      // validator: (value) {
      //   return value!.trim().length > 0 ? null : "用户名不能为空";
      // },
    );
  }

  Widget _getTopImageWidget() {
    return Image.asset(
      "assets/images/login_bg.jpeg",
      width: double.infinity,
      height: 260,
      fit: BoxFit.fill,
    );
  }
}
